<template>
  <div class="warp-box  clearfix">
    <div class="warp-con">
      <div class="header">
        <div class="headerWrapper">
          <div class="search">
            <el-form :inline="true" class="demo-form-inline">
              <el-form-item>
                <el-input v-model="name" placeholder="请输入真实姓名" @keyup.enter.native="getUserPage" auto-complete="off" clearable/>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="getUserPage">查询</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="add">新增</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div class="content">
        <el-table :data="tableData" :header-row-style="HeaderStyle" :row-style='cellStyle' stripe tooltip-effect="dark" border>
          <el-table-column align="center" prop="name" show-overflow-tooltip label="真实姓名"/>
          <el-table-column align="center" prop="account" show-overflow-tooltip label="登录名"/>
          <el-table-column align="center" prop="departName" show-overflow-tooltip label="所属部门"/>
          <el-table-column align="center" prop="roleNams" show-overflow-tooltip label="角色">
            <template slot-scope="scope">
              {{scope.row.roleNames != null ? scope.row.roleNames.join(',') : ''}}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="mobilePhoneNo" show-overflow-tooltip label="手机号码"/>
          <el-table-column align="center" prop="sex" show-overflow-tooltip label="性别">
            <template slot-scope="scope">
              {{scope.row.sex | sexFilter}}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="idCardNo" show-overflow-tooltip label="身份证号码"/>
          <el-table-column label="操作" align="center" min-width="130">
            <template slot-scope="scope">
              <span @click="updatePassword(scope.row)" class="pointer">修改密码</span><i class="line"></i>
              <span @click="edit(scope.row)" class="pointer">修改</span><i class="line"></i>
              <span @click="deleteUser(scope.row)" class="pointer">删除</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="paging">
        <el-pagination :page-sizes="[10]" :page-size="this.pageSize" :current-page="pageIndex"
                       :total="totalCount" @current-change="pager" background
                       layout="total, sizes, prev, pager, next, jumper" />
      </div>
    </div>
    <el-dialog :visible.sync="dialogVisible" :title="formTitle" :before-close="cancel" :close-on-click-modal="false">
      <el-form :model="dataForm" :rules="rules" ref="dataForm" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="name">
              <el-input v-model="dataForm.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录名" prop="account">
              <el-input v-model="dataForm.account" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="formEdit === 'add'">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="dataForm.password" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="RePassword">
              <el-input type="password" v-model="dataForm.RePassword" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="mobilePhone">
              <el-input v-model="dataForm.mobilePhoneNo" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCardNo">
              <el-input v-model="dataForm.idCardNo" :change="getBirthdayFromIdNum()" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="dataForm.sex" placeholder="请选择">
                <el-option v-for="(item, i) in genderData" :key="i" :label="item.label" :value="item.val" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="departmentId">
              <SelectTree :options="departmentData" :value="dataForm.departmentId" :clearable="true" :accordion="false" @getValue="getValue($event)"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="职能" prop="rank">
              <el-select v-model="dataForm.rank" filterable placeholder="请选择">
                <el-option v-for="(item, i) in rankData" :key="i" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="userIds">
              <el-select v-model="dataForm.roleIds" multiple filterable placeholder="请选择">
                <el-option v-for="item in roleData" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="formEdit == 'edit'" class="dialogBtn" type="primary" @click="updateUser">修 改</el-button>
        <el-button v-else type="primary" @click="addUser" class="dialogBtn">添 加</el-button>
        <el-button type="primary" @click="cancel" class="dialogBtn">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="修改密码" :visible.sync="editVisible" width="30%" :before-close="cancelEdit">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="100px">
        <el-form-item label="登录名" prop="account">
          <el-input v-model="editForm.account" disabled />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="editForm.password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="rePassword">
          <el-input type="password" v-model="editForm.rePassword" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="dialogBtn" type="primary" @click="changePassword">修 改</el-button>
        <el-button type="primary" @click="cancelEdit" class="dialogBtn">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import systemApi from '@/api/systemApi'
import SelectTree from '@/components/TreeSelect'
export default {
  components: {
    SelectTree
  },
  data () {
    var validateAccount = (rule, value, callback) => {
      let uPattern = /^[a-zA-Z0-9_]{2,16}$/ // 用户名正则，6到16位（字母，数字，下划线）
      if (!value) {
        return callback(new Error('登录名不能为空！'))
      } else {
        if (uPattern.test(value) === false) {
          callback(new Error('登录名应为2到16位（字母，数字，下划线）'))
        } else {
          callback()
        }
      }
    }
    var validatePhone = (rule, value, callback) => {
      let uPattern = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
      if (!value) {
        return callback(new Error('手机号码不能为空！'))
      } else {
        if (uPattern.test(value) === false) {
          callback(new Error('请输入正确的手机号码'))
        } else {
          callback()
        }
      }
    }
    var validatePass = (rule, value, callback) => {
      if (this.detailEditType === 'edit') {
        callback()
      } else {
        let pPattern = /^[a-zA-Z0-9_]{6,16}$/ // 密码正则，6到16位（字母，数字，下划线）
        if (!value || value === '') {
          callback(new Error('密码不能为空！'))
        } else {
          if (pPattern.test(value) === false) {
            callback(new Error('6到16位（字母，数字，下划线）'))
          } else {
            callback()
          }
        }
      }
    }
    var validateRePass = (rule, value, callback) => {
      if (this.detailEditType === 'edit') {
        callback()
      } else {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.dataForm.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
    }
    var validateRePassTow = (rule, value, callback) => {
      if (!value || value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.editForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      name: null,
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      tableData: [],
      loading: false,
      cellStyle: {height: '60px', fontSize: '16px'},
      HeaderStyle: {height: '70px', fontSize: '16px'},
      dataForm: {},
      formTitle: null,
      formEdit: 'detail',
      dialogVisible: false,
      rules: {
        name: [
          {required: true, message: '真实姓名', trigger: 'blur'}
        ],
        account: [
          {validator: validateAccount, required: true, trigger: 'blur'}
        ],
        mobilePhoneNo: [
          {validator: validatePhone, required: true, trigger: 'blur'}
        ],
        password: [
          {validator: validatePass, required: true, trigger: 'blur'}
        ],
        RePassword: [
          {validator: validateRePass, required: true, trigger: 'blur'}
        ]
      },
      genderData: [
        {label: '未知', val: 0},
        {label: '男', val: 1},
        {label: '女', val: 2}
      ],
      departmentData: [],
      roleData: [],
      rankData: ['助理级', '中级', '副高级', '正级'],
      editForm: {},
      editVisible: false,
      editRules: {
        password: [
          {validator: validatePass, required: true, trigger: 'blur'}
        ],
        rePassword: [
          {validator: validateRePassTow, required: true, trigger: 'blur'}
        ]
      }
    }
  },
  filters: {
    sexFilter (val) {
      let str
      let vals = val + ''
      switch (vals) {
        case '1':
          str = '男'
          break
        case '2':
          str = '女'
          break
        default:
          str = '未知'
      }
      return str
    }
  },
  created () {
    this.findPage()
  },
  methods: {
    pager (val) {
      this.pageIndex = val
      this.findPage()
    },
    getUserPage () {
      this.pageIndex = 1;
      this.pageSize = 10;
      this.findPage();
    },
    findPage () {
      let params = {
        name: this.name,
        pageIndex: this.pageIndex,
        pageSize: this.pageSize
      }
      this.showLoading('正在查询中')
      systemApi.findPageUser(params).then(res => {
        let result = res.data.result
        if (res.data.message === 'success' && result) {
          this.tableData = result.rows
          this.totalCount = result.totalCount
        } else {
          this.totalCount = 0
          this.tableData = []
        }
        this.hideLoading()
      })
    },
    getDepartment () {
      this.departmentData = []
      systemApi.getDeparmentList().then((res) => {
        if (res.data.message === 'success') {
          this.departmentData = res.data.result
        }
      })
    },
    getRole () {
      this.roleData = []
      systemApi.findRoleList().then((res) => {
        if (res.data.message === 'success') {
          this.roleData = res.data.result
        }
      })
    },
    add () {
      this.formEdit = 'add'
      this.formTitle = '新增用户'
      this.getRole()
      this.getDepartment()
      this.dialogVisible = true
    },
    edit (row) {
      this.formEdit = 'edit'
      this.formTitle = '修改用户'
      this.getRole()
      this.getDepartment()
      systemApi.getUser(row.id).then(res => {
        if (res.data.message === 'success') {
          this.dataForm = res.data.result
          this.dialogVisible = true
        }
      })
    },
    getBirthdayFromIdNum () {
      let birthday
      let idCardNo = this.dataForm.idCardNo
      if (idCardNo) {
        if (idCardNo.length === 18) {
          birthday = idCardNo.substr(6, 8)
        }
        birthday = birthday.replace(/(.{4})(.{2})/, '$1-$2-')
        this.dataForm.birthday = birthday
      } else {
        this.dataForm.birthday = undefined
      }
    },
    getValue (value) {
      this.dataForm.departmentId = value
    },
    cancel () {
      this.dataForm = {}
      this.dialogVisible = false
    },
    addUser () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.showLoading('正在保存')
          let params = Object.assign({}, this.dataForm)
          systemApi.addUser(params).then((res) => {
            this.hideLoading()
            if (res.data.message === 'success') {
              this.findPage()
              this.cancel()
              this.$notify({
                title: '消息',
                message: ('添加成功!'),
                position: 'bottom-right',
                showClose: false,
                type: 'success'
              })
            } else {
              this.$notify.error({
                title: '消息',
                message: '添加失败'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    updateUser () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let params = this.dataForm
          this.showLoading('正在修改')
          systemApi.updateUser(params).then((res) => {
            this.hideLoading()
            if (res.data.message === 'success') {
              this.findPage()
              this.cancel()
              this.$notify({
                title: '消息',
                message: ('操作成功!'),
                position: 'bottom-right',
                showClose: false,
                type: 'success'
              })
            } else {
              this.$notify.error({
                title: '消息',
                message: '修改失败'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    deleteUser (row) {
      let tips = ''
      if (row) {
        tips = `此操作将删除: ${row.name}, 是否继续?`
      } else {
        return
      }
      this.$confirm(tips, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        systemApi.deleteUser(row.id).then((res) => {
          if (res.data.message === 'success') {
            this.findPage()
            this.$notify({
              title: '消息',
              message: ('删除成功！'),
              position: 'bottom-right',
              showClose: false,
              type: 'success'
            })
          }
        })
      }).catch((error) => {
        console.log(error)
      })
    },
    updatePassword (row) {
      this.editForm = row
      this.editVisible = true
    },
    cancelEdit () {
      this.editForm = {}
      this.editVisible = false
    },
    changePassword () {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          let params = {
            id: this.editForm.id,
            password: this.editForm.password
          }
          this.showLoading('正在修改')
          systemApi.editUser(params).then((res) => {
            this.hideLoading()
            if (res.data.message === 'success') {
              this.findPage()
              this.cancelEdit()
              this.$notify({
                title: '消息',
                message: ('修改成功!'),
                position: 'bottom-right',
                showClose: false,
                type: 'success'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    showLoading (message) {
      this.$loading({
        lock: true,
        text: message,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    hideLoading () {
      this.$loading().close()
    }
  }
}
</script>
<style lang="less" scoped>
  .search {
    & /deep/ .el-form-item__label {
      font-size: 1.8rem;
    }
  }

  .f-g-sd1 {
    position: relative;
    float: left;
    width: 95px;
    margin-right: -95px;
  }

  .f-g-mn1 {
    float: right;
    width: 100%;
  }

  .f-g-mn1c {
    margin-left: 100px;
  }

  .detail-body {
    color: rgba(250, 250, 250, 0.9);

    &::after {
      content: '';
      display: block;
      visibility: hidden;
      height: 0;
      clear: both;
    }
  }

  .item-inline {
    width: 50%;
    float: left;
    margin-bottom: 20px;

    .item-name {
      display: inline-block;
    }

    .item-context {
      display: inline-block;
    }
  }

  .no-data {
    text-align: center;
    font-size: 14px;

    .tips {
      padding: 20px 0px;
      color: #666;
    }
  }

  .el-form-item__label {
    padding: 0 20px 0 0 !important;
  }

  .content {
    margin-top: 10px;

    & /deep/ .el-checkbox__inner {
      height: 20px;
      width: 20px;
      font-size: 28px;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);
      background: none;
    }

    & /deep/ .el-tooltip__popper {
      background-color: red;
    }

    & /deep/ .el-checkbox__inner::after {
      border-width: 2px;
      height: 6px;
      left: 6px;
      top: 3px;
      width: 4px;
    }

    & /deep/ .el-checkbox__input.is-indeterminate .el-checkbox__inner::before {
      top: 8px;
      background: white;
    }
  }

  .line {
    display: inline-flex;
    height: 21px;
    width: 1px;
    background: rgba(0, 255, 255, 1);
    margin: 0 10px;
    vertical-align: middle;
  }

  .dialogBtn {
    font-size: 1.6rem;

    &:hover {
      background: rgba(12, 161, 151, 1);
    }
  }
</style>
<style lang="less">
  /**
   * 修改样式   覆盖默认的饿了么全局样式
   */
  .el-form-item__label {
    padding: 0 20px 0 0 !important;
  }
</style>
